//
//  YMHomeViewController.m
//  YMMedical
//
//  Created by y s on 2023/6/19.
//

#import "YMHomeViewController.h"
#import "YMGuideLaunchView.h"
#import "YMHomeBindDeviceAlert.h"
#import "YMHomeNavgationBar.h"
#import "YMHomeSegementView.h"
#import "YMHomeHealthOneCell.h"
#import "YMHomeHealthMoreCell.h"
#import "YMHomeFileAndVideoCell.h"
#import "YMHomeSectionHeadView.h"
#import "YMHomeIntroduceCell.h"
#import "YMHomeRecordListCell.h"
#import "YMHomeService.h"
#import "YMCheckService.h"


typedef NS_ENUM(NSUInteger, YMHomeSectionType) {
    YMHomeSectionType_Health = 0,
    YMHomeSectionType_Menu,
    YMHomeSectionType_Introduce,
    YMHomeSectionType_Record,
};

@interface YMHomeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) YMHomeNavgationBar *navBar;
@property (nonatomic, strong) YMHomeSegementView *vSegement;

@property (nonatomic, strong) UITableView *tvMain;
/** 无设备时 绑定新设备弹窗 */
@property (nonatomic, strong) YMHomeBindDeviceAlert *alertBind;

@property (nonatomic, assign) NSInteger segementIndex;
@property (nonatomic, strong) NSArray *arrSegement;
@property (nonatomic, strong) NSArray *arrBanner;
@property (nonatomic, assign) NSInteger bannerIndex;

@property (nonatomic, copy) NSString *testeeId;

@property (nonatomic, strong) NSDictionary *dictRecord;
@property (nonatomic, copy) NSString *minorTermId;

@property (nonatomic, strong) NSDictionary *dictFirst;

@end

@implementation YMHomeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self addNotify];
    [self setGuide];
    [self loadData];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self checkHadDevice];
    [self.navBar refreshData];
}

#pragma mark -- UI
- (void)setUI{
    self.navBarHidden = YES;
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.vSegement];
    [self.view addSubview:self.tvMain];
    
    [self.vSegement mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo([SFitUtil fit:15]);
        make.top.mas_equalTo([SFitUtil fit:15]+TOP_BAR_HEIGHT);
        make.right.mas_equalTo([SFitUtil fit:-15]);
        make.height.mas_equalTo([SFitUtil fit:48]);
    }];
    [self.tvMain mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.vSegement.mas_bottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
    WEAK_SELF;
    [SThemeUtil refershHead:self.tvMain block:^{
        [weakSelf loadData];
    }];
}
- (void)addNotify{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessAction) name:LoginedNoti_key object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessAction) name:kLanguage_change object:nil];
}


- (void)loadData{
    if (self.arrSegement == nil || self.arrSegement.count < 1){
        [self loadSegmentData];
    }else{
        [self loadInforData:NO];
    }
}

- (void)loadSegmentData{
    WEAK_SELF;
    self.segementIndex = 0;
    [YMHomeService requestHomeSegementDataWithSuccess:^(NSArray * _Nonnull arrData) {
        if (arrData.count > 0){
            weakSelf.arrSegement = arrData;
            weakSelf.vSegement.arrList = arrData;
            if (weakSelf.segementIndex > arrData.count-1){
                weakSelf.segementIndex = 0;
            }
            weakSelf.vSegement.indexNow = weakSelf.segementIndex;
            [weakSelf loadFirstOneData];
        }else{
            [weakSelf.tvMain.mj_header endRefreshing];
        }
    } failure:^(NSString * _Nonnull message) {
        [weakSelf.tvMain.mj_header endRefreshing];
        [SHUD showInfo:message];
    }];
}
- (void)loadInforData:(BOOL)isFirst{
    NSString *segementId = @"";
    self.bannerIndex = 0;
    if (self.segementIndex < self.arrSegement.count){
        NSDictionary *dict = [SDataUtil dictOf:self.arrSegement[_segementIndex]];
        segementId = [SDataUtil stringOf:dict[@"id"] valid:@""];
    }
    WEAK_SELF;
    [YMHomeService requestHomeItemInforWithSegementID:segementId success:^(NSArray * _Nonnull arrData) {
        [weakSelf.tvMain.mj_header endRefreshing];
        weakSelf.arrBanner = arrData;
        if (isFirst && weakSelf.dictFirst != nil){
            NSString *minorTermId = [SDataUtil stringOf:weakSelf.dictFirst[@"minorTermId"] valid:@""];
            for (NSDictionary *item in arrData) {
                NSString *idStr = [SDataUtil stringOf:item[@"id"] valid:@""];
                if ([idStr isEqualToString:minorTermId]){
                    weakSelf.bannerIndex = [arrData indexOfObject:item];
                }
            }
        }
        [weakSelf getCurrentSelectId];
        [weakSelf.tvMain reloadData];
    } failure:^(NSString * _Nonnull message) {
        [weakSelf.tvMain.mj_header endRefreshing];
        [SHUD showInfo:message];
    }];
}
//最近一次检测记录
- (void)loadTestRecordData{
    NSString *minorTermId = @"";
    if (_bannerIndex < self.arrBanner.count){
        NSDictionary *dictTemp = [SDataUtil dictOf:self.arrBanner[_bannerIndex]];
        minorTermId = [SDataUtil stringOf:dictTemp[@"id"]];
    }
    if (minorTermId == nil || minorTermId.length < 1 ||
        self.testeeId == nil || self.testeeId.length < 1){
        self.dictRecord = nil;
        [self.tvMain reloadData];
        return;
    }
    WEAK_SELF;
    [YMHomeService requestLatelyHealthRecordDetailsDetectionUserId:self.testeeId minorTermId:minorTermId success:^(NSDictionary * _Nonnull dictData) {
        weakSelf.dictRecord = dictData;
        [weakSelf.tvMain reloadData];
    } failure:^(NSString * _Nonnull message) {
        
    }];
}
//选中被测人后 默认的检测项目
- (void)loadFirstOneData{
    if (self.testeeId == nil || self.testeeId.length < 1){
        [self loadInforData:NO];
        return;
    }
    WEAK_SELF;
    [YMHomeService requestHomegetOneMinorTermDetails:self.testeeId success:^(NSDictionary * _Nonnull dictData) {
        weakSelf.dictFirst = dictData;
        [weakSelf updateFirstSegementIndex];
        [weakSelf loadInforData:YES];
    } failure:^(NSString * _Nonnull message) {
        [weakSelf loadInforData:NO];
    }];
}
//引导页
- (void)setGuide{
    [YMGuideLaunchView showFinishBlock:^{
        [YMBridging goLogin];
    }];
}
- (void)loginSuccessAction{
    self.arrSegement = [[NSArray alloc] init];
    self.testeeId = @"";
    [self.navBar refreshData];
    [self loadData];
    [self checkHadDevice];
}

- (void)checkHadDevice{
    if ([YMMyModel isLogin] == NO){
        if (self.alertBind != nil){
            [self.alertBind dismiss];
        }
        return;
    }
    WEAK_SELF;
    [YMHomeService requestHomeHadAddDeviceDataSuccess:^(BOOL hadDevice,NSArray *arrDevice) {
        if (hadDevice == NO){
            if (weakSelf.alertBind == nil){
                weakSelf.alertBind = [[YMHomeBindDeviceAlert alloc] init];
            }
            [weakSelf.alertBind show];
        }else{
            [weakSelf.alertBind dismiss];
        }
        weakSelf.navBar.arrDevice = arrDevice;
    } failure:^(NSString * _Nonnull message) {
        
    }];
}

//当前小类id
- (void)getCurrentSelectId{
    if (self.bannerIndex < self.arrBanner.count){
        NSDictionary *dictTemp = [SDataUtil dictOf:self.arrBanner[self.bannerIndex]];
        self.minorTermId = [SDataUtil stringOf:dictTemp[@"id"] valid:@""];
    }else{
        self.minorTermId = @"";
    }
    [self loadTestRecordData];
}

- (void)updateFirstSegementIndex{
    NSString *firstMinorTermId = [SDataUtil stringOf:self.dictFirst[@"firstMinorTermId"]];
    for (int i = 0; i < self.arrSegement.count; i++) {
        NSDictionary *item = [SDataUtil dictOf:self.arrSegement[i]];
        NSString *termId = [SDataUtil stringOf:item[@"id"]];
        if ([termId isEqualToString:firstMinorTermId]){
            self.segementIndex = i;
            self.vSegement.indexNow = self.segementIndex;
        }
    }
}

#pragma mark -- UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return YMHomeSectionType_Record+1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAK_SELF;
    if (indexPath.section == YMHomeSectionType_Health){
        if (self.arrBanner.count > 1){
            YMHomeHealthMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMHomeHealthMoreCell" forIndexPath:indexPath];
            cell.arrItem = self.arrBanner;
            cell.currentIndex = self.bannerIndex;
            cell.changeItemBlock = ^(NSInteger index) {
                weakSelf.bannerIndex = index;
                [weakSelf getCurrentSelectId];
            };
            return cell;
        }else{
            YMHomeHealthOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMHomeHealthOneCell" forIndexPath:indexPath];
            cell.arrItem = self.arrBanner;
            return cell;
        }
    }else if (indexPath.section == YMHomeSectionType_Menu){
        YMHomeFileAndVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMHomeFileAndVideoCell" forIndexPath:indexPath];
        cell.idStr = self.minorTermId;
        if (self.segementIndex < self.arrSegement.count){
            NSDictionary *dict = [SDataUtil dictOf:self.arrSegement[_segementIndex]];
            cell.maxIdStr = [SDataUtil stringOf:dict[@"id"] valid:@""];
        }else{
            cell.maxIdStr = @"";
        }
        cell.testeeId = self.testeeId;
        [cell updateLanguage];
        return cell;
    }else if (indexPath.section == YMHomeSectionType_Introduce){
        YMHomeIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMHomeIntroduceCell" forIndexPath:indexPath];
        if (_bannerIndex < self.arrBanner.count){
            NSDictionary *dictTemp = [SDataUtil dictOf:self.arrBanner[_bannerIndex]];
            cell.strIntroduce = [SDataUtil stringOf:dictTemp[@"77ewilfzt61i7exb"]];
        }
        return cell;
    }else if (indexPath.section == YMHomeSectionType_Record){
        if (self.dictRecord != nil && self.dictRecord.count > 0){
            YMHomeRecordListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMHomeRecordListCell" forIndexPath:indexPath];
            cell.dict = self.dictRecord;
            return cell;
        }
    }
    return [[UITableViewCell alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == YMHomeSectionType_Introduce){
        YMHomeSectionHeadView *view = [[YMHomeSectionHeadView alloc] init];
        view.strTitle = KLanguage(@"pdt_intro_txt");
        return view;
    }else if (section == YMHomeSectionType_Record){
        if (self.dictRecord != nil && self.dictRecord.count > 0){
            YMHomeSectionHeadView *view = [[YMHomeSectionHeadView alloc] init];
            view.strTitle = KLanguage(@"last_dete_txt");
            return view;
        }
    }
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAK_SELF;
    if (indexPath.section == YMHomeSectionType_Health){
        if (self.arrBanner.count > 1){
            
            return [YMHomeHealthMoreCell getCellHeight];
        }else{
            return [YMHomeHealthOneCell getCellHeight];
        }
    }else if (indexPath.section == YMHomeSectionType_Menu)
    {
        return [YMHomeFileAndVideoCell getCellHeight];
    }else if (indexPath.section == YMHomeSectionType_Introduce)
    {
        return [tableView fd_heightForCellWithIdentifier:@"YMHomeIntroduceCell" configuration:^(YMHomeIntroduceCell *cell) {
            if (weakSelf.bannerIndex < weakSelf.arrBanner.count){
                NSDictionary *dictTemp = [SDataUtil dictOf:weakSelf.arrBanner[weakSelf.bannerIndex]];
                cell.strIntroduce = [SDataUtil stringOf:dictTemp[@"77ewilfzt61i7exb"]];
            }
        }];
    }else if (indexPath.section == YMHomeSectionType_Record)
    {
        if (self.dictRecord != nil && self.dictRecord.count > 0){
            
            return [tableView fd_heightForCellWithIdentifier:@"YMHomeRecordListCell" configuration:^(YMHomeRecordListCell *cell) {
                cell.dict = weakSelf.dictRecord;
            }];
        }
    }
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == YMHomeSectionType_Introduce){
        return [SFitUtil fit:45];
    }else if (section == YMHomeSectionType_Record){
        if (self.dictRecord != nil && self.dictRecord.count > 0){
            return [SFitUtil fit:45];
        }
    }
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
#pragma mark -- setter and getter
- (YMHomeNavgationBar *)navBar{
    if (_navBar == nil){
        _navBar = [[YMHomeNavgationBar alloc] init];
        WEAK_SELF;
        _navBar.changeUserBlock = ^(NSString * _Nonnull userId) {
            if (weakSelf.testeeId == nil || weakSelf.testeeId.length < 1){
                weakSelf.testeeId = userId;
                [weakSelf loadFirstOneData];
            }else{
                weakSelf.testeeId = userId;
            }
            [YMMyModel shared].homeUserId = userId;
            [weakSelf loadTestRecordData];
        };
    }
    return _navBar;
}
- (YMHomeSegementView *)vSegement{
    if (_vSegement == nil){
        _vSegement = [[YMHomeSegementView alloc] init];
        _vSegement.backgroundColor = STheme.D9;
        _vSegement.clipsToBounds = YES;
        _vSegement.layer.cornerRadius = [SFitUtil fit:8];
        WEAK_SELF;
        _vSegement.segementClickBlock = ^(NSInteger index) {
            weakSelf.segementIndex = index;
            [weakSelf loadInforData:NO];
        };
    }
    return _vSegement;
}
- (UITableView *)tvMain{
    if (!_tvMain) {
        _tvMain = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tvMain.backgroundColor = [UIColor clearColor];
        _tvMain.delegate   = self;
        _tvMain.dataSource = self;
        _tvMain.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tvMain.showsVerticalScrollIndicator   = NO;
        _tvMain.showsHorizontalScrollIndicator = NO;
        _tvMain.estimatedRowHeight = 0;
        _tvMain.estimatedSectionHeaderHeight = 0;
        _tvMain.estimatedSectionFooterHeight = 0;
        _tvMain.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tvMain.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, [SFitUtil fit:30])];
        
        [_tvMain registerClass:[YMHomeHealthOneCell class] forCellReuseIdentifier:@"YMHomeHealthOneCell"];
        [_tvMain registerClass:[YMHomeHealthMoreCell class] forCellReuseIdentifier:@"YMHomeHealthMoreCell"];
        [_tvMain registerClass:[YMHomeFileAndVideoCell class] forCellReuseIdentifier:@"YMHomeFileAndVideoCell"];
        [_tvMain registerClass:[YMHomeIntroduceCell class] forCellReuseIdentifier:@"YMHomeIntroduceCell"];
        [_tvMain registerClass:[YMHomeRecordListCell class] forCellReuseIdentifier:@"YMHomeRecordListCell"];
    }
    return _tvMain;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
